package com.msb.juc.c_026;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class T08_CompletableFuture {
    public static void main(String[] args) {
        long start, end;

        start = System.currentTimeMillis();

        priceOfTM();
        priceOfJD();
        priceOfTB();

        end = System.currentTimeMillis();
        System.out.println("use serial method call!" + (end - start));

        start = System.currentTimeMillis();
        CompletableFuture<Double> futureTM = CompletableFuture.supplyAsync(() -> priceOfTM());
        CompletableFuture<Double> futureTB = CompletableFuture.supplyAsync(() -> priceOfTB());
        CompletableFuture<Double> futureJD = CompletableFuture.supplyAsync(() -> priceOfJD());

        // 全部完成后再进行
        CompletableFuture.allOf(futureJD, futureTB, futureTM).join();

        // 异步逐步执行
        CompletableFuture.supplyAsync(() -> priceOfTM())
                .thenApply(String::valueOf)
                .thenApply(str -> "price" + str)
                .thenAccept(System.out::println);

        end = System.currentTimeMillis();
        System.out.println("use completeble future!" + (end - start));

        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static void delay() {
        int time = new Random().nextInt(500);
        try {
            TimeUnit.MILLISECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("After %s sleep!\n", time);
    }

    public static double priceOfTM() {
        delay();
        return 1.00;
    }

    public static double priceOfTB() {
        delay();
        return 2.00;
    }

    public static double priceOfJD() {
        delay();
        return 3.00;
    }


}
